from common.pagenation import Paging
from daos import get_db_session
from models.system_log import SystemLog
from models.system_user import SystemUser


def add_system_log(log_orm: SystemLog, is_commit=True):
    session = get_db_session()

    session.add(log_orm)
    session.commit() if is_commit else session.flush()
    return log_orm


def query_system_log_with_page(data_param) -> Paging:
    filter_s = []

    if data_param.get('module'):
        filter_s.append(SystemLog.module == data_param.get('module'))

    if data_param.get('operator'):
        filter_s.append(SystemUser.real_name.contains(data_param.get('operator')))

    if data_param.get('create_time_start'):
        filter_s.append(SystemLog.create_time >= data_param.get('create_time_start'))

    if data_param.get('create_time_end'):
        filter_s.append(SystemLog.create_time <= data_param.get('create_time_end'))

    session = get_db_session()
    return session.query(SystemLog) \
        .join(SystemUser, SystemLog.operator == SystemUser.id) \
        .filter(*filter_s) \
        .order_by(SystemLog.id.desc()) \
        .paginate(page=data_param.get('page'), per_page=data_param.get('page_size'), error_out=False)
